package com.demo.springBootDemo06.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.demo.springBootDemo06.entity.Dept;
import com.demo.springBootDemo06.service.DeptService;
import com.demo.springBootDemo06.utils.CommonResult;

@RestController
@RequestMapping("/dept")
public class DeptController {

	@Autowired
	private DeptService deptService;

	@RequestMapping(method = RequestMethod.GET)
	public Object depts() {
		CommonResult<List<Dept>> result = new CommonResult<>();
		try {
			result.setData(deptService.findList());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/{deptno}", method = RequestMethod.GET)
	public Object id(@PathVariable("deptno") Integer deptno) {
		CommonResult<Dept> result = new CommonResult<>();
		try {
			result.setData(deptService.getByPrimaryKey(deptno));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "", method = RequestMethod.POST)
	public Object add(@RequestBody final Dept dept) {
		CommonResult<Dept> result = new CommonResult<>();
		try {
			result.setData(deptService.addDept(dept));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/{deptno}", method = RequestMethod.PUT)
	// PUT请求:Form表单不支持Put方法,使用@RequestBody接收参数
	public Object update(@PathVariable("deptno") Integer deptno, @RequestBody Dept dept) {
		CommonResult<Dept> result = new CommonResult<>();
		try {
			result.setData(deptService.updateDept(deptno, dept));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/{deptno}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("deptno") Integer deptno) {
		CommonResult<Dept> result = new CommonResult<>();
		try {
			result.setData(deptService.deleteByPrimaryKey(deptno));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
